//
//  MyConsultListViewController.m
//  安好
//
//  Created by lianchuang on 14/11/18.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyConsultListViewController.h"
#import "MyConsultViewCell.h"
#import "AppDelegate.h"
#import "YXJSON.h"
#import "ChatContent.h"
#import "PeerList.h"
#import "ConsultList.h"
#import "ConsultingChatViewController.h"
#import "LCStatusBarOverlay.h"
#import "FMDatabaseQueue.h"
#import "SystemMessageCenter.h"
#import "LoginViewController.h"
#import "ConsultViewController.h"
@interface MyConsultListViewController ()<ChatDelegate>

@end

@implementation MyConsultListViewController
{
    UILabel *labelBG;
    NoConsultListView *noConsultListView;
}
-(void)viewWillAppear:(BOOL)animated
{
    [self app];
    self.dataArray=[ConsultList readAllConsultList];
    if (self.dataArray.count<=0) {
        self.tableview.hidden=YES;
    }
    else
    {
        noConsultListView.hidden=YES;
    }
    [self.tableview reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [[LCStatusBarOverlay shared] hidenMessageLabel];
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.navigationItem.title=@"我的咨询";
    
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;

    
    self.dataArray = [[NSMutableArray alloc] init];
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    [self.tableview setBackgroundColor:[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16]];
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (kScreenHeight==480) {
        self.tableview.frame=CGRectMake(0, 0, kScreenWidth,CGRectGetHeight(self.view.frame));
    }else
    {
        self.tableview.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
    [self inntLabelCenter];
}
- (void)inntLabelCenter
{
    if (IPhone6Plus) {
        noConsultListView=[[[NSBundle mainBundle]loadNibNamed:@"NoConsultListView" owner:self options:nil]lastObject];

    }else{
        noConsultListView=[[[NSBundle mainBundle]loadNibNamed:@"NoConsultListView" owner:self options:nil] objectAtIndex:0];

    }
    noConsultListView.noListLabel.textColor=TITLE_ARTICLE_CONTENTFONT_COLOR;

    [noConsultListView.consultSender addTarget:self action:@selector(clickConsult:) forControlEvents:UIControlEventTouchUpInside];
//    noConsultListView.frame=CGRectMake((kScreenWidth-320)/2, (kScreenHeight-96-64)/2, noConsultListView.width, noConsultListView.height);
    
    CGPoint point=CGPointMake(kScreenWidth/2, kScreenHeight/2-64);
    noConsultListView.center=point;
    [self.view addSubview:noConsultListView];
}
/**
 *  无咨询记录时，点击去咨询跳转资讯首页（判断有咨询资格->实名认证->完成任务）
 */
- (void)clickConsult:(UIButton *)sender
{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *mobile_certification=[NSString stringWithFormat:@"%@",[userdefault valueForKey:@"authentication"]];
    if ([mobile_certification isEqualToString:@"1"]){
        ConsultViewController *consult=[[ConsultViewController alloc]initWithNibName:@"ConsultViewController" bundle:[NSBundle mainBundle]];
        [self.navigationController pushViewController:consult animated:YES];
    }else
    {
        LoginViewController * loginViewController = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [self presentViewController:loginViewController animated:YES completion:^{
        }];
        loginViewController.realName.isFromRegist=NO;
        [loginViewController showRealNameView];
    }
}
- (AppDelegate *)app
{
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=self;
    return app;
}
- (void)receiveMessage:(AppDelegate *)appD Message:(id)message
{

    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //判断同行or非同行 。type=1同行；type=2医患关系。
    //    ConsultList *consultList=[[ConsultList alloc]initWithDictionary:dict];
    NSString *readStatus;
    if ([[dict objectForKey:@"type"] intValue] == 1) {
        readStatus=@"1";
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                //加入耗时操作
                NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                CGSize size;
                if ([[messageDic valueForKey:@"pic"]length]>0) {
                    size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                }
                else{
                    [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                }
            });
            [PeerList updatePeerList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];

        });
    }else
    {
        if ([ConsultList isExistItem:dict AndDb:[MyFMDB openDB]]) {
            readStatus=@"1";
        }else
        {
            readStatus=@"1";
        }
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            
            if ([ConsultList updateConsultList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                self.dataArray=[ConsultList readAllConsultList];
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                if (self.dataArray.count>0) {
                    noConsultListView.hidden=YES;
                    self.tableview.hidden=NO;
                }
                [self.tableview reloadData];
            }
            NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
            if ([meth isEqualToString:@"9"]) {
                return;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //加入耗时操作
                NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                CGSize size;
                if ([[messageDic valueForKey:@"pic"]length]>0) {
                    size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                }
                else{
                    [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                }
            });
        });
    }

}
- (void)receiveRemoteNotificationMessage:(AppDelegate *)appD Message:(id)message
{
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //遍历消息内容数组，排序后将消息插入数据库（如果和当前用户是同一人，并展示聊天消息）
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    //    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    dispatch_async(q1, ^{
        NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
        for (int index=0; index<array1.count; index++) {
            NSString *keys=[array1 objectAtIndex:index];
            if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
            {
                //在其他界面收到聊天消息，只进行存取数据（2个表）
                NSMutableDictionary *MutDic=[NSMutableDictionary dictionaryWithDictionary:[[dict objectForKey:@"history"] objectForKey:keys]];
                [MutDic setValue:@"2" forKey:@"messageDirection"];
                NSString *messageType;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"message"] length] > 0) {
                    messageType = @"1";
                } else if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"pic"] length] > 0) {
                    messageType = @"2";
                } else {
                    messageType = @"3";
                }
                [MutDic setValue:messageType forKey:@"messageType"];
                //判断同行or非同行 。type=1同行；type=2医患关系。
                NSString *readStatus;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys]  objectForKey:@"type"] intValue] == 1) {
                    readStatus=@"1";
                    
                            //加入耗时操作
                            NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                            CGSize size;
                            if ([[messageDic valueForKey:@"pic"]length]>0) {
                                size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                                [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                                [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                                [queue inDatabase:^(FMDatabase *db) {
                                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];

                                }];
                            }
                            else{
                                [queue inDatabase:^(FMDatabase *db) {
                                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                                }];
                            }
                    [queue inDatabase:^(FMDatabase *db) {
                        [PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];

                    }];
                }else
                {
                    if ([ConsultList isExistItem:[[dict objectForKey:@"history"] objectForKey:keys] AndDb:[MyFMDB openDB]]) {
                        readStatus=@"1";
                    }else
                    {
                        readStatus=@"1";
                    }
                            //加入耗时操作
                            NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                            CGSize size;
                            if ([[messageDic valueForKey:@"pic"]length]>0) {
                                size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                                [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                                [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                                
                                [queue inDatabase:^(FMDatabase *db) {
                                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                                    if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                                    }
                                }];

                            }
                            else{
                                [queue inDatabase:^(FMDatabase *db) {
                                    
                                    if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                                        NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                                        if ([meth isEqualToString:@"9"]) {
                                            return;
                                        }
                                        [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                                    }
                                }];
                            }
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataArray=[ConsultList readAllConsultList];
            if (self.dataArray.count>0) {
                noConsultListView.hidden=YES;
                self.tableview.hidden=NO;
            }
            [self.tableview reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];

        });
    });
}
//刷新页面，并跳转到最后一行
- (void)skiptableviewBottom
{
    [self.tableview reloadData];
    
    if (self.dataArray.count > 0) {
        [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
#pragma mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyConsultViewCell *consultCell=[tableView dequeueReusableCellWithIdentifier:@"consultcell"];
    if (!consultCell) {
        if (kScreenWidth==414) {
            consultCell=[[[NSBundle mainBundle] loadNibNamed:@"MyConsultViewCell" owner:self options:nil] lastObject];
        }
        else{
            consultCell=[[[NSBundle mainBundle] loadNibNamed:@"MyConsultViewCell" owner:self options:nil] objectAtIndex:0];
        }
    }
    
    ConsultList *consultList = [self.dataArray objectAtIndex:indexPath.row];
    if (consultList.departmentname.length<=0) {
        consultList.departmentname=@"未指定科室";
    }
    if (consultList.username.length<=0) {
        consultCell.department_doctor.text=[NSString stringWithFormat:@"%@",consultList.departmentname];
    }else
    {
        consultCell.department_doctor.text=[NSString stringWithFormat:@"%@ | %@",consultList.departmentname,consultList.username];
    }
    consultCell.content.text=consultList.message;
    if ([consultList.consultType isEqualToString:@"1"]) {
        consultCell.consultType.text=@"视频咨询";
        consultCell.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#ff9d9d"];
    }else if ([consultList.consultType isEqualToString:@"0"])
    {
        consultCell.consultType.text=@"图文咨询";
        consultCell.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#4fc1e9"];
    }
    NSDate *nowDate = [NSDate date];
    int seconds ;
    NSString *tim1=[NSString stringWithFormat:@"%f",[consultList.dateline doubleValue]];
    if (tim1.length>19) {
        seconds=  nowDate.timeIntervalSince1970 - [consultList.dateline doubleValue]/10000;
    }else
    {
        seconds=  nowDate.timeIntervalSince1970 - [consultList.dateline doubleValue];
    }
    
    if(seconds < 60) {
        consultCell.date.text = @"刚刚";
    } else if(seconds < 60*60) {
        consultCell.date.text = [NSString stringWithFormat:@"%d分钟前", seconds/60%60];
    } else if(seconds < 24*60*60) {
        consultCell.date.text = [NSString stringWithFormat:@"%d小时前", seconds/60/60%24];
    } else if(seconds < 4*24*60*60) {
        consultCell.date.text = [NSString stringWithFormat:@"%d天前", seconds/60/60/24%4];
    } else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        NSString *tim1=[NSString stringWithFormat:@"%f",[consultList.dateline doubleValue]];
        if (tim1.length>19) {
            tim1=[NSString stringWithFormat:@"%f",[consultList.dateline doubleValue]/10000];
        }else
        {
            tim1=consultList.dateline;
        }
        NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:tim1.integerValue]];
        consultCell.date.text = dateString;
    }
    if ([consultList.noread isEqualToString:@"-1"]) {
        consultCell.readstatus.text=@"待回复";
        consultCell.readImage.hidden=YES;
    }else if ([consultList.noread isEqualToString:@"0"])
    {
        consultCell.readstatus.text=@"已回复";
        consultCell.readImage.hidden=YES;
    }else if ([consultList.noread isEqualToString:@"1"])
    {
        consultCell.readImage.hidden=NO;
        consultCell.readstatus.text=@"新回复";
    }
    consultCell.selectionStyle=UITableViewCellSelectionStyleNone;
    return consultCell;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 5)];
    view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth==414) {
        return 150;
    }
    return 125.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ConsultList *consultList = [self.dataArray objectAtIndex:indexPath.row];
    if ([consultList.noread isEqual:@"1"]) {
        [ConsultList resetUnreadCountWithUid:consultList.qid];
    }
    ConsultingChatViewController * consultingViewController = [[ConsultingChatViewController alloc]init];
    consultingViewController.userName = consultList.username;
    consultingViewController.qid = consultList.qid;
    consultingViewController.doctoruid = consultList.uid;
    consultingViewController.titeleString = consultList.username;
    NSString * docid = consultList.uid;
    if ([docid length] <= 0) {
        consultingViewController.touid = consultList.uid;
    }else{
        consultingViewController.touid = docid;
    }
    consultingViewController.toTpye = @"2";
    consultingViewController.toMed = @"0";
    consultingViewController.isFromwhere=1;
    consultingViewController.consultType=consultList.consultType;
    [self.navigationController pushViewController:consultingViewController animated:YES];

}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        ConsultList *consultList=[self.dataArray objectAtIndex:indexPath.row];
        [self.dataArray removeObject:consultList];
                [ConsultList deleteConsultListWithQid:consultList.qid];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        if ([consultList.noread isEqualToString:@"1"]) {
            LCStatusBarOverlay *statusBar=[LCStatusBarOverlay shared];
            NSString *qid=[NSString stringWithFormat:@"%@",[statusBar.dic valueForKey:@"qid"]];
            if ([consultList.qid isEqualToString:qid]) {
                [statusBar hidenMessageLabel];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
        }
        if (self.dataArray.count<=0) {
            noConsultListView.hidden=NO;
        }
    }
}
- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
